package handlers

import (
	"data_service/models"
	"data_service/server"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

// 初始化消息业务服务
var chatService = server.NewChatService()

// SendMessageHandler 发送消息
func SendMessageHandler(c *gin.Context) {
	var req struct {
		RoomID   uint   `json:"room_id" binding:"required"`
		UserID   int    `json:"user_id" binding:"required"`
		UserName string `json:"user_name"`
		Content  string `json:"content" binding:"required"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数错误"})
		return
	}
	msg := &models.Message{
		RoomID:   req.RoomID,
		UserID:   req.UserID,
		UserName: req.UserName,
		Content:  req.Content,
		Time:     time.Now(),
	}
	if err := chatService.SendMessage(msg); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "消息发送失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{"message": "消息发送成功"})
}

// GetRoomMessagesHandler 获取房间消息历史
func GetRoomMessagesHandler(c *gin.Context) {
	roomIDStr := c.Query("room_id")
	limitStr := c.DefaultQuery("limit", "20")
	roomID, _ := strconv.Atoi(roomIDStr)
	limit, _ := strconv.Atoi(limitStr)
	msgs, err := chatService.GetRoomMessages(uint(roomID), limit)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取消息失败"})
		return
	}
	c.JSON(http.StatusOK, msgs)
}
